'use strict'

const { ApiController } = require('jax')

class AdminMenuController extends ApiController {
  get Model() {
    return this.ctx.model.AdminMenu
  }

  // 分类树
  async tree() {
    const { ctx } = this
    const where = this.getFilter()

    const returnData = await this.Model.tree({
      where,
      sort: {
        isTop: 'DESC',
        rank: 'ASC',
      },
    })

    ctx.body = {
      code: 0,
      msg: 'success',
      data: returnData,
    }
  }

  // 分类列表
  async index() {
    const { ctx } = this
    const where = this.getFilter()

    const returnData = await this.Model.children({
      where,
      sort: {
        isTop: 'DESC',
        rank: 'ASC',
      },
    })

    ctx.body = {
      code: 0,
      msg: 'success',
      data: returnData,
    }
  }

  // 获取查询条件
  getFilter() {
    const { ctx } = this
    const { query, helper } = ctx
    const { admin } = ctx.state
    const where = {}

    // 角色权限菜单
    if (query.action == 'role_auth_menu') {
      if (this.isSuperAdmin) {
        query.systemType = query.systemType || admin.systemType
      } else {
        query.systemType = admin.systemType
      }
    }

    // 匹配搜索
    ;['isOpen', 'systemType'].map((key) => {
      if (query[key] && !query[key] == '') where[key] = query[key]
    })

    return where
  }

  // 保存前
  async beforeSave() {
    const { ctx } = this
    const { body } = ctx.request

    if (body.parentId && body.parentId == body.menuId) throw '所选分类不能是自己'
  }

  // 保存后
  async afterSave() {
    const { ctx } = this
    const { body } = ctx.request
  }
}

module.exports = AdminMenuController
